//
//  ADTableViewController.m
//  ADKit
//
//  Created by 杜 泽旭 on 2017/12/3.
//  Copyright © 2017年 duzexu. All rights reserved.
//

#import "ADTableViewController.h"
#import "ADKitHeaders.h"

@interface ADTableViewController () {
    BOOL emptyDataSetInit;
}

@property (nonatomic, readwrite, weak)  UITableView *tableView;
@property (nonatomic, readonly, strong) ADTableViewModel *viewModel;

@end

@implementation ADTableViewController
@dynamic viewModel;

- (void)dealloc {
    _tableView.dataSource = nil;
    _tableView.delegate = nil;
}

/// override
- (void)initialize {
    [super initialize];
    [self ad__setupSubViews];
    if (self.viewModel.shouldFetchLocalDataOnViewModelInitialize) {
        [self.viewModel.requestLocalDataCommand execute:nil];
    }
    if ([self.viewModel shouldRequestRemoteDataOnViewDidLoad] && !self.viewModel.shouldPullDownToRefresh) {
        [self.viewModel.requestRemoteDataCommand execute:@1];
    }
}

- (void)bindViewModel {
    [super bindViewModel];
    @weakify(self)
    /// 隐藏emptyView
    [[self.viewModel.requestRemoteDataCommand.executing skip:1] subscribeNext:^(NSNumber *executing) {
        @strongify(self)
        UIView *emptyDataSetView = [self.tableView.subviews.rac_sequence objectPassingTest:^(UIView *view) {
            return [NSStringFromClass(view.class) isEqualToString:@"DZNEmptyDataSetView"];
        }];
        emptyDataSetView.alpha = 1.0 - executing.floatValue;
    }];
    
    [self.viewModel.requestRemoteDataCommand.executionSignals.switchToLatest subscribeNext:^(id _) {
        @strongify(self);
        self.viewModel.networkReachable = YES;
    }];

    [self.viewModel.requestRemoteDataCommand.errors subscribeNext:^(id _) {
        @strongify(self);
        self.viewModel.networkReachable = self.viewModel.services.reachabilityManager.reachable;
    }];
    
    [[self.viewModel.reloadIndexPaths deliverOnMainThread] subscribeNext:^(id x) {
        @strongify(self);
        if ([x isKindOfClass:[NSArray class]]) {
            [self.tableView reloadRowsAtIndexPaths:x withRowAnimation:UITableViewRowAnimationNone];
        }else if ([x isKindOfClass:[NSIndexPath class]]) {
            [self.tableView reloadRowAtIndexPath:x withRowAnimation:UITableViewRowAnimationNone];
        }else{
            [self reloadData];
        }
    }];
    [[self.viewModel.insertIndexPaths deliverOnMainThread] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [self.tableView beginUpdates];
        if ([x isKindOfClass:[NSArray class]]) {
            [self.tableView insertRowsAtIndexPaths:x withRowAnimation:UITableViewRowAnimationNone];
        }else if ([x isKindOfClass:[NSIndexPath class]]) {
            [self.tableView insertRowsAtIndexPaths:@[x] withRowAnimation:UITableViewRowAnimationNone];
        }
        [self.tableView endUpdates];
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    UIView *emptyDataSetView = [self.tableView.subviews.rac_sequence objectPassingTest:^(UIView *view) {
        return [NSStringFromClass(view.class) isEqualToString:@"DZNEmptyDataSetView"];
    }];
    if (emptyDataSetView && !emptyDataSetInit) {
        emptyDataSetInit=YES;
        emptyDataSetView.alpha = 0;
    }
}

#pragma mark - 设置子控件
- (void)ad__setupSubViews {
    // set up tableView
    UITableView *tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:self.viewModel.style];
    tableView.backgroundColor = self.view.backgroundColor;
    tableView.separatorStyle = self.viewModel.separatorStyle;
    tableView.contentInset  = self.viewModel.contentInset;
    // 注册cell
    [self.viewModel registTableViewCell:tableView];
    // set delegate and dataSource
    tableView.delegate = self.viewModel;
    tableView.dataSource = self.viewModel;
    tableView.tableFooterView = [UIView new];
    [self.view addSubview:tableView];
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(self.viewModel.tableViewViewInset);
    }];
    
    /// 占位
    tableView.emptyDataSetDelegate = self.viewModel;
    tableView.emptyDataSetSource = self.viewModel;
    
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 7.0, *)) {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    tableView.estimatedRowHeight = 0;
    tableView.estimatedSectionHeaderHeight = 0;
    tableView.estimatedSectionFooterHeight = 0;
    
    self.tableView = tableView;
    
    /// 添加加载和刷新控件
    if (self.viewModel.shouldPullDownToRefresh) {
        @weakify(self);
        Class cls = self.viewModel.refreshHeaderClass;
        MJRefreshHeader *header;
        if (cls) {
            header = [cls headerWithRefreshingBlock:^{
                @strongify(self);
                [self tableViewDidTriggerHeaderRefresh];
            }];
        }else{
            header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
                @strongify(self);
                [self tableViewDidTriggerHeaderRefresh];
            }];
        }
        self.tableView.mj_header = header;
        [self.tableView.mj_header beginRefreshing];
    }
    
    if (self.viewModel.shouldPullUpToLoadMore) {
        @weakify(self);
        Class cls = self.viewModel.refreshFooterClass;
        MJRefreshFooter *footer;
        if (cls) {
            footer = [cls footerWithRefreshingBlock:^{
                @strongify(self);
                [self tableViewDidTriggerFooterRefresh];
            }];
        }else{
            footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                @strongify(self);
                [self tableViewDidTriggerFooterRefresh];
            }];
        }
        footer.hidden = YES;
        self.tableView.mj_footer = footer;
        /// 隐藏footer or 无更多数据
        RAC(self.tableView.mj_footer, hidden) = [[RACObserve(self.viewModel, noMoreData)
          deliverOnMainThread] map:^id(id value) {
            @strongify(self)
            if (self.viewModel.shouldEndRefreshingWithNoMoreData) return @(0);
            return [value boolValue] ? @(1) : @(0);
        }];
    }
}

#pragma mark - 上下拉刷新事件
- (void)tableViewDidTriggerHeaderRefresh {
    @weakify(self)
    [[[self.viewModel.requestRemoteDataCommand
       execute:@1]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         self.viewModel.page = 1;
         if (self.viewModel.shouldEndRefreshingWithNoMoreData) {
             [self.tableView.mj_footer resetNoMoreData];
         }
     } error:^(NSError *error) {
         @strongify(self)
         [self.tableView.mj_header endRefreshing];
     } completed:^{
         @strongify(self)
         [self.tableView.mj_header endRefreshing];
         [self _requestDataCompleted];
     }];
}

- (void)tableViewDidTriggerFooterRefresh {
    @weakify(self);
    [[[self.viewModel.requestRemoteDataCommand
       execute:@(self.viewModel.page + 1)]
      deliverOnMainThread]
     subscribeNext:^(id x) {
         @strongify(self)
         self.viewModel.page += 1;
     } error:^(NSError *error) {
         @strongify(self);
         [self.tableView.mj_footer endRefreshing];
     } completed:^{
         @strongify(self)
         [self.tableView.mj_footer endRefreshing];
         /// 请求完成
         [self _requestDataCompleted];
     }];
}

#pragma mark - sub class can override it
- (void)reloadData {
    [self.tableView reloadData];
}

#pragma mark - 辅助方法
- (void)_requestDataCompleted {
    if (self.viewModel.shouldEndRefreshingWithNoMoreData && self.viewModel.noMoreData) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
    if (self.viewModel.noMoreData && self.viewModel.dataSource.count == 0) {
        self.tableView.mj_footer.hidden = YES;
    }
    [self.viewModel requestDataCompleted];
}

@end
